package com.csx.data.orm.jpa.base.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.csx.data.orm.jpa.base.entity.User;
import com.csx.data.orm.jpa.base.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    // 查询1: 根据 单个唯一键属性 查询获取 唯一数据. 1  —>  1
    public User findById(Long id) {
        Optional<User> user = userRepository.findById(id);
        return user.orElse(null);
    }

    public List<User> findAllByIds(List<Long> ids) {
        Iterable<User> users = userRepository.findAllById(ids);
        return StreamSupport.stream(users.spliterator(), false)
                .collect(Collectors.toList());
    }

    // 查询2: 根据 单个非唯一属性 查询获取 多条数据. 1  —>  n
    public List<User> findByFirstNameIgnoreCase(String firstName) {
        return userRepository.findByFirstNameIgnoreCase(firstName);
    }

    public List<User> findByFirstNameIn(List<String> firstNames) {
        return userRepository.findByFirstNameIn(firstNames);
    }

    // 查询3: 根据 多个非唯一属性 查询获取 唯一数据. n  —>  1
    public User findByFirstNameAndLastName(String firstName, String lastName) {
        Optional<User> user = userRepository.findByFirstNameAndLastName(firstName, lastName);
        return user.orElse(null);
    }

    // 查询4: 根据 多个非唯一属性 查询获取 多条数据. n  —>  n
    public List<User> findByAgeAndCity(int age, String city) {
        return userRepository.findByAgeAndCity(age, city);
    }

    // 查询5: 查询并排序
    public List<User> findByFirstNameOrderByLastNameAsc(String firstName) {
        return userRepository.findByFirstNameOrderByLastNameAsc(firstName);
    }
    public List<User> findByFirstNameSortedByFirstNameAsc(String firstName) {
        Sort sort = Sort.by(Sort.Direction.ASC, "firstName");
        return userRepository.findByFirstName(firstName, sort);
    }

    // 查询6: 分页查询
    public Page<User> findAllWithPage(int page, int size) {
        Pageable pageable = PageRequest.of(page, size);
        return userRepository.findAll(pageable);
    }

    // 查询7: 模糊查询
    public List<User> findByFirstNameContainingIgnoreCase(String keyword) {
        return userRepository.findByFirstNameContainingIgnoreCase(keyword);
    }

    // 查询8: 通过 Specification 实现 多条件灵活查询(条件存在则拼接上去,否则不拼接该条件)
    public List<User> findAll(String firstName, String lastName, Integer age, String city) {
        Specification<User> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();

            if (StrUtil.isNotBlank(firstName)) {
                predicates.add(criteriaBuilder.equal(root.get("firstName"), firstName));
            }

            if (StrUtil.isNotBlank(lastName)) {
                predicates.add(criteriaBuilder.equal(root.get("lastName"), lastName));
            }

            if (ObjectUtil.isNotEmpty(age)) {
                predicates.add(criteriaBuilder.equal(root.get("age"), age));
            }

            if (StrUtil.isNotBlank(city)) {
                predicates.add(criteriaBuilder.equal(root.get("city"), city));
            }

            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };

        return userRepository.findAll(spec);
    }

    // ************************************ 新增/修改数据 ******************************************************
    // 新增/修改1: 新增/修改 单条数据
    public User save(User user) {
        return userRepository.save(user);
    }

    // 新增/修改2: 新增/修改 多条数据
    public List<User> saveAll(List<User> users) {
        return userRepository.saveAll(users);
    }

    // 新增/修改3: 新增/修改 多条数据 (真批量)
    public List<User> saveAllInBatch(List<User> users) {

        return null;
    }

    // ************************************ 删除数据 ******************************************************
    // 删除1: 根据 主键 删除 单条数据
    public void deleteById(Long id) {
        userRepository.deleteById(id);
    }

    // 删除2: 根据 主键列表 删除 多条数据
    public void deleteAllById(List<Long> ids) {
        userRepository.deleteAllById(ids);
    }

    // 删除3: 根据 非主键 删除 多条数据
    @Transactional
    public void deleteByLastName(String lastName) {
        userRepository.deleteByLastName(lastName);
    }

    // 删除4: 根据 实体 删除数据
    public void delete(User user) {
        userRepository.delete(user);
    }

    // 删除5: 根据 实体列表 删除数据
    public void deleteAll(List<User> users) {
        userRepository.deleteAll(users);
    }


    @Autowired
    private DataSource dataSource;

    public User getUser(long id) {
        try (Connection connection = dataSource.getConnection();
             PreparedStatement statement = connection.prepareStatement("SELECT * FROM user WHERE id = ?")) {
            statement.setLong(1, id);
            try (ResultSet resultSet = statement.executeQuery()) {
                if (resultSet.next()) {
                    User user = new User();
                    user.setId(resultSet.getLong("id"));
                    user.setFirstName(resultSet.getString("first_name"));
                    return user;
                }
            }
        } catch (SQLException e) {
            // 处理异常
        }
        return null;
    }
}
